<template>
  <div class="notice-page">
    <el-button type="primary" @click="dialogVisible1 = true"
      >添加公告</el-button
    >
    <el-table :data="tableData" border style="width: 100%">
      <el-table-column prop="id" label="编号" width="300px"></el-table-column>
      <el-table-column
        prop="create_time"
        label="创建时间"
        width="180"
      ></el-table-column>
      <el-table-column prop="update_time" label="修改时间"></el-table-column>
      <el-table-column prop="content" label="信息"></el-table-column>
      <el-table-column prop="state" label="状态">
        <template v-slot="scope">
          <el-switch
            v-model="scope.row.state"
            :active-value="1"
            :inactive-value="0"
            active-color="#13ce66"
            inactive-color="#ff4949"
            disabled
          ></el-switch>
        </template>
      </el-table-column>
      <el-table-column width="180" label="操作">
        <template slot-scope="scope">
          <el-button @click="edit(scope.row.id)" size="small" type="primary"
            >编辑</el-button
          >
          <el-button @click="del(scope.row.id)" size="small" type="danger"
            >删除</el-button
          >
        </template>
      </el-table-column>
    </el-table>

    <!-- 分页组件 -->
    <el-pagination
      @size-change="handleSizeChange"
      @current-change="handleCurrentChange"
      :current-page="currentPage"
      :page-sizes="[10, 20]"
      :page-size="pageSize"
      layout="total, sizes, prev, pager, next"
      :total="total"
    ></el-pagination>

    <!-- 新增公告弹出层 -->
    <el-dialog title="新增公告" :visible.sync="dialogVisible1" width="30%">
      <el-form
        :model="addInfo"
        ref="addInfo"
        label-width="100px"
        class="demo-dynamic"
      >
        <el-form-item
          prop="content"
          label="公告信息"
          :rules="[{ required: true, message: '请输入公告信息' }]"
        >
          <el-input type="text" v-model="addInfo.content"></el-input>
        </el-form-item>
        <el-form-item
          prop="state"
          label="是否推荐"
          :rules="[{ required: true, message: '1为推荐、2为不推荐' }]"
        >
          <el-input type="number" v-model="addInfo.state"></el-input>
        </el-form-item>
      </el-form>
      <span slot="footer" class="dialog-footer">
        <el-button type="primary" @click="addNotice">确 定</el-button>
      </span>
    </el-dialog>

    <!-- 修改某公告弹出层 -->
    <el-dialog title="修改公告" :visible.sync="dialogVisible" width="30%">
      <el-form
        :model="reviseInfo"
        ref="reviseInfo"
        label-width="100px"
        class="demo-dynamic"
      >
        <el-form-item
          prop="content"
          label="公告信息"
          :rules="[{ required: true, message: '请输入公告信息' }]"
        >
          <el-input type="text" v-model="reviseInfo.content"></el-input>
        </el-form-item>
        <el-form-item
          prop="state"
          label="是否推荐"
          :rules="[{ required: true, message: '1为推荐、2为不推荐' }]"
        >
          <el-input type="number" v-model="reviseInfo.state"></el-input>
        </el-form-item>
      </el-form>
      <span slot="footer" class="dialog-footer">
        <el-button type="primary" @click="uploadNotice">确 定</el-button>
      </span>
    </el-dialog>
  </div>
</template>

<script>
import { getNotice, delNotice, reviseNotice, addNotice } from "@/api/users";
export default {
  data() {
    return {
      noticeList: [],
      dialogVisible: false,
      dialogVisible1: false,
      addInfo: {
        content: "",
        state: "",
      },
      reviseInfo: {
        id: "",
        content: "",
        state: "",
      },
      // 当前页码，初始化为1
      currentPage: 1,
      // 每页显示的条数，默认设置为10，可选项还有20
      pageSize: 10,
      // 总数据条数，初始为0，后续根据接口返回数据更新
      total: 0,
      // 用于表格展示的当前页数据
      tableData: [],
    };
  },
  methods: {
    // 时间处理函数
    formatDate(dateString) {
      if (dateString === null) {
        // 如果时间为 null，返回空字符串
        return "";
      }
      const date = new Date(dateString);
      if (isNaN(date.getTime())) {
        // 如果传入的时间字符串无效，返回默认时间或者提示信息
        return "无效的时间";
      }
      const year = date.getFullYear();
      const month = String(date.getMonth() + 1).padStart(2, "0");
      const day = String(date.getDate()).padStart(2, "0");
      const hours = String(date.getHours()).padStart(2, "0");
      const minutes = String(date.getMinutes()).padStart(2, "0");
      const seconds = String(date.getSeconds()).padStart(2, "0");
      return `${year}-${month}-${day} ${hours}:${minutes}:${seconds}`;
    },
    // 获取所有公告信息
    getNoticeAll() {
      getNotice()
        .then((res) => {
          this.noticeList = res.noticeList.map((notice) => ({
            ...notice,
            create_time: this.formatDate(notice.create_time),
            update_time: this.formatDate(notice.update_time)
          }));

          this.total = this.noticeList.length;
          this.getTableData();
        })
        .catch((err) => {
          console.log(err);
        });
    },
    // 根据当前页码和每页显示条数获取当前页数据
    getTableData() {
      const start = (this.currentPage - 1) * this.pageSize;
      const end = start + this.pageSize;
      this.tableData = this.noticeList.slice(start, end);
    },
    // 每页条数改变时的处理函数
    handleSizeChange(val) {
      this.pageSize = val;
      this.currentPage = 1;
      this.getTableData();
    },
    // 当前页码改变时的处理函数
    handleCurrentChange(val) {
      this.currentPage = val;
      this.getTableData();
    },
    // 编辑某条公告
    edit(id) {
      // console.log(id)
      this.dialogVisible = true;
      this.reviseInfo.id = id;
    },
    // 新增公告
    async addNotice() {
      // console.log(this.addInfo)
      try {
        const res = await addNotice(this.addInfo);
        this.getNoticeAll();
        // console.log(res)
        this.dialogVisible1 = false;
        this.addInfo = { content: "", state: "" };
      } catch (error) {
        console.log(error);
      }
    },
    async uploadNotice() {
      try {
        const res = await reviseNotice(this.reviseInfo);
        this.getNoticeAll();
        // console.log(res)
        this.dialogVisible = false;
      } catch (error) {
        console.log(error);
      }
    },
    // 删除某条公告
    del(id) {
      delNotice(id)
        .then((res) => {
          // console.log(res)
          this.getNoticeAll();
        })
        .catch((err) => {
          console.log(err);
        });
    },
  },
  created() {
    this.getNoticeAll();
  },
};
</script>

<style scoped>
/* 整体页面容器样式 */
.notice-page {
  padding: 20px;
  background-color: #f8f9fa;
}

/* 按钮样式 */
.el-button {
  margin-bottom: 10px;
  border-radius: 4px;
  padding: 6px 12px;
  transition: all 0.3s ease;
}
.el-button:hover {
  opacity: 0.8;
  box-shadow: 0 2px 4px rgba(0, 0, 0, 0.15);
}

/* 表格样式 */
.el-table {
  background-color: white;
  border-radius: 5px;
  box-shadow: 0 2px 5px rgba(0, 0, 0, 0.1);
  margin-bottom: 20px;
}
.el-table th {
  background-color: #f0f0f0;
  color: #333;
  font-weight: normal;
  text-align: center;
  padding: 12px 0;
}
.el-table td {
  text-align: center;
  padding: 10px 0;
}
.el-table.el-switch {
  margin: 0 auto;
}
.el-table.el-button {
  margin: 0 5px;
  padding: 6px 12px;
  border-radius: 3px;
  transition: all 0.3s ease;
}
.el-table.el-button:hover {
  opacity: 0.8;
  box-shadow: 0 2px 4px rgba(0, 0, 0, 0.15);
}

/* 分页组件样式 */
.el-pagination {
  text-align: center;
  margin-top: 10px;
}
.el-pagination.is-background.el-pager li {
  background-color: #f0f0f0;
  color: #333;
  border-radius: 3px;
  margin: 0 3px;
  transition: all 0.3s ease;
}
.el-pagination.is-background.el-pager li:hover {
  background-color: #e0e0e0;
  cursor: pointer;
}
.el-pagination.is-background.el-pager li.active {
  background-color: #13ce66;
  color: white;
}
.el-pagination button:disabled {
  opacity: 0.6;
  cursor: not-allowed;
}

/* 弹出层通用样式 */
.el-dialog {
  border-radius: 5px;
  box-shadow: 0 0 10px rgba(0, 0, 0, 0.2);
}
.el-dialog.el-form {
  padding: 20px;
}
.el-dialog.el-form-item {
  margin-bottom: 20px;
}
.el-dialog.el-form-item label {
  font-weight: bold;
  color: #333;
}
.el-dialog.el-input {
  width: 100%;
  border-radius: 4px;
  border: 1px solid #ccc;
  padding: 8px 10px;
}
.el-dialog.dialog-footer {
  display: flex;
  justify-content: flex-end;
  padding: 10px 20px;
}
.el-dialog.dialog-footer.el-button {
  margin-left: 10px;
  border-radius: 4px;
  padding: 6px 12px;
  transition: all 0.3s ease;
}
.el-dialog.dialog-footer.el-button:hover {
  opacity: 0.8;
  box-shadow: 0 2px 4px rgba(0, 0, 0, 0.15);
}
</style>